package com.qf.team2.netdisc.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5工具类
 *
 * @author Simon_Wong
 * @date 2021/05/26 10:29
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class MD5Util {
    /**
     * 文件md5生成器
     *
     * @param file 文件
     * @return {@link String}
     */
    public static String md5(File file) {
        //生成一个md5加密器
        try {
            FileInputStream in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md = MessageDigest.getInstance("MD5");
            //计算MD5 的值
            md.update(byteBuffer);
            //BigInteger 将8位的字符串 转成16位的字符串 得到的字符串形式是哈希码值
            //BigInteger(参数1,参数2) 参数1 是 1为正数 0为0 -1为负数
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串md5生成器
     *
     * @param plainText 纯文本
     * @return {@link String}
     */
    public static String md5(String plainText) {
        byte[] secretBytes;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个算法");
        }
        StringBuilder s = new StringBuilder(new BigInteger(1, secretBytes).toString());
        System.out.println(32 - s.length());
        for (int i = 0; i < 32 - s.length(); i++) {
            s.insert(0, "0");
        }
        return s.toString();
    }
}
